<template>
  <el-main>
    <p></p>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input
          v-model="search"
          placeholder="搜索水费梯度"
          clearable
          @input="fetchRates"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="openDialog('add')">
          <el-icon><Plus /></el-icon>添加
        </el-button>
      </el-form-item>
    </el-form>

    <p></p>
    <el-table :data="tableData" class="table" style="width: 99%" border>
      <el-table-column label="电费编号">
        <template #default="scope">
          <span>{{ scope.row.waId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="梯度">
        <template #default="scope">
          <span>{{ scope.row.step }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下限(度)">
        <template #default="scope">
          <span>{{ scope.row.down }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上限(度)">
        <template #default="scope">
          <span>{{ scope.row.up }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单价(¥)">
        <template #default="scope">
          <span>{{ scope.row.pri }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期">
        <template #default="scope">
          <div style="display: flex; align-items: center">
            <el-icon><Timer /></el-icon>
            <span style="margin-left: 10px">{{ formatDate(scope.row.creDate) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openDialog('edit', scope.row)">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <p></p>
    <div style="margin-top: 10px">
      <el-button mb-2 @click="toggle" class="switch">Switch Language</el-button>
      <br />

      <el-config-provider :locale="locale">
        <el-col span="8" :offset="8">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next, jumper"
            :total="total"
          />
        </el-col>
      </el-config-provider>
    </div>

    <!-- 添加/编辑弹出框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="水费编号" prop="waId">
          <el-input v-model.number="form.waId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="梯度">
          <el-input v-model="form.step" type="string"></el-input>
        </el-form-item>
        <el-form-item label="下限(度)" prop="down">
          <el-input v-model.number="form.down" type="number"></el-input>
        </el-form-item>
        <el-form-item label="上限(度)" prop="up">
          <el-input v-model.number="form.up" type="number"></el-input>
        </el-form-item>
        <el-form-item label="单价(¥)" prop="pri">
          <el-input v-model.number="form.pri" type="number"></el-input>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-input v-model="form.creDate"></el-input>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </el-main>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from "vue";
import { Delete, Edit, Plus, Search, Timer } from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import en from "element-plus/dist/locale/en.mjs";
import apiClient from "@/api"; // 引入 Axios 实例
import dayjs from "dayjs"; // 引入 dayjs

const language = ref("zh-cn");
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));

const toggle = () => {
  language.value = language.value === "zh-cn" ? "en" : "zh-cn";
};

interface User {
  waId: number;
  step: string;
  down: number;
  up: number;
  pri: number;
  creDate: string;
}

const tableData = ref<User[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const search = ref("");

const fetchRates = async () => {
  try {
    const response = await apiClient.get("/waPrice", {
      params: { page: currentPage.value, size: pageSize.value, search: search.value },
    });
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.error(error);
  }
};

const handlePageChange = async (page: number) => {
  currentPage.value = page;
  await fetchRates();
};

const dialogVisible = ref(false);
const dialogTitle = ref("");
const form = reactive<User>({
  waId: 0,
  step: "",
  down: 0,
  up: 0,
  pri: 0,
  creDate: "",
});

const rules = reactive({
  waId: [
    { required: true, message: "水费编号不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "水费编号不能为负数", trigger: "blur" },
  ],
  down: [
    { required: true, message: "下限不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "下限不能为负数", trigger: "blur" },
  ],
  up: [
    { required: true, message: "上限不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "上限不能为负数", trigger: "blur" },
  ],
  pri: [
    { required: true, message: "单价不能为空", trigger: "blur" },
    { type: "number", min: 0, message: "单价不能为负数", trigger: "blur" },
  ],
});

const formRef = ref(null);

const openDialog = (type: string, row?: User) => {
  if (type === "add") {
    dialogTitle.value = "添加";
    Object.assign(form, {
      waId: 0,
      step: "",
      down: 0,
      up: 0,
      pri: 0,
      creDate: "",
    });
  } else if (type === "edit" && row) {
    dialogTitle.value = "编辑";
    Object.assign(form, row);
  }
  dialogVisible.value = true;
};

const handleSave = async () => {
  if (form.waId < 0 || form.down < 0 || form.up < 0 || form.pri < 0) {
    ElMessage.error("电费编号、下限、上限和单价不能为负数");
    return;
  }
  try {
    await formRef.value.validate();
    if (dialogTitle.value === "添加") {
      await apiClient.post("/waPrice/add", form);
    } else if (dialogTitle.value === "编辑") {
      await apiClient.put("/waPrice/update", form);
    }
    dialogVisible.value = false;
    fetchRates();
  } catch (error) {
    console.error(error);
  }
};

const handleDelete = async (index: number, row: User) => {
  try {
    await apiClient.delete(`/waPrice/${row.waId}`);
    fetchRates();
  } catch (error) {
    console.error(error);
  }
};

const formatDate = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
};

onMounted(() => {
  fetchRates();
});
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
.switch {
  display: none;
}
</style>
